package com.cube.reactive.guide.publisher;

import java.util.concurrent.*;
import java.util.function.Supplier;

/**
 * @author cube.li
 * @since 2024/6/2 9:50
 */
public class PeriodPublisher<T> extends SubmissionPublisher<T> {

    final ScheduledFuture<?> periodicTask;

    final ScheduledExecutorService scheduler;

    PeriodPublisher(Executor executor, int maxBufferCapacity,
                    Supplier<? extends T> supplier,
                    long period, TimeUnit unit) {
        super(executor, maxBufferCapacity);
        scheduler = new ScheduledThreadPoolExecutor(1);
        periodicTask = scheduler.scheduleAtFixedRate(
                () -> submit(supplier.get()), 0, period, unit);
    }

    @Override
    public void close() {
        periodicTask.cancel(false);
        scheduler.shutdown();
        super.close();
    }
}
